#include <head.h>

#define BUFFER_SIZE 1028 
  
void copy_file(int fd_1, int fd_2, int offset) 
{  
    lseek(fd_1, offset, SEEK_SET);
    char buffer[BUFFER_SIZE];  
    ssize_t num_read;  
    while ((num_read = read(fd_1, buffer, BUFFER_SIZE)) > 0) 
    {  
        write(fd_2, buffer, num_read);  
    }  
  
    close(fd_1);  
    close(fd_2);  
}  
  
int main(int argc, char *argv[]) 
{  
    if (argc != 3) 
    {  
        fprintf(stderr, "Usage: %s file_1 file_2\n", argv[0]);  
        return 1;  
    }  
  
    int fd_1 = open(argv[1], O_RDONLY);  
    if (fd_1 == -1) 
    {  
        perror("Failed to open file_1");  
        return 1;  
    }  
  
    int fd_2 = open(argv[2], O_WRONLY | O_CREAT | O_TRUNC, 0644);  
    if (fd_2 == -1) 
    {  
        perror("Failed to open file_2");  
        close(fd_1);  
        return 1;  
    }  
  
    int procs = 2; 
    pid_t pids[procs];  
    
    // 子进程
    for (int i = 0; i < procs; i++) 
    {  
        pids[i] = fork();      
        if (pids[i] == 0) 
        {   
            copy_file(fd_1, fd_2, i * BUFFER_SIZE);
            exit(0);  
        } else if (pids[i] == -1) 
        {  
            perror("Failed to fork");  
            return 1;  
        }  
    }  
    // 父进程  
    for (int i = 0; i < procs; i++) 
    {  
        waitpid(pids[i], NULL, 0);  
    }  
  
    close(fd_1);  
    close(fd_2);  
  
    return 0;  
}